<template>
  <div class="container">
    <div class="header">
      <div class="header-left-item">
        <div><img id="user-avatar-img" :src="circleUrl" alt="" /></div>
        <div>
          <h2>新闻档案录入</h2>
        </div>
      </div>
      <div class="header-right-item">
        <el-upload
          class="upload-demo"
          ref="upload"
          :limit="1"
          :action="uploadUrl"
          :auto-upload="false"
          :on-exceed="handleExceed"
          :before-upload="beforeAvatarUpload"
          :headers="token"
          :on-success="uploadSuccess"
        >
          <el-button round slot="trigger" size="small" type="primary"
            >选取头像</el-button
          >
          <el-button
            round
            style="margin-left: 10px"
            size="small"
            type="success"
            @click="submitUpload"
            >提交</el-button
          >
          <div slot="tip" class="el-upload__tip">
            仅限jpg/jpeg/png文件,且不超过2MB
          </div>
        </el-upload>
      </div>
    </div>
    <div class="my-content">
      <div class="my-content-item">
        <el-form label-position="right" label-width="90px" :model="userInfo">
          <el-form-item label="姓名">
            <el-input v-model="userInfo.username"></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-radio-group v-model="userInfo.gender">
              <el-radio label="男">
                <li class="el-icon-male"></li>
                男
              </el-radio>
              <el-radio label="女"
                ><li class="el-icon-female"></li>
                女
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="userInfo.email"></el-input>
          </el-form-item>
          <el-form-item label="身份证">
            <el-input v-model="userInfo.idCard"></el-input>
          </el-form-item>
          <el-form-item label="出生日期">
            <!-- <el-input v-model="userInfo.birthday"></el-input> -->
            <el-date-picker
              v-model="userInfo.birthday"
              type="date"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="家庭住址">
            <el-input v-model="userInfo.address"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="success" size="small" round @click="updateInfo"
              >提 交</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import {
  updateManagerInfo,
  getUserInfo,
  downloadAvatar,
  getUserDetails,
  updateUserInfo,
} from "@/api";
import { getToken } from "@/utils/token";
import { AVATAR_UPLOAD_PATH } from "@/utils/constants";
import { validEmail, validIdCard } from "@/utils/validate";
export default {
  data() {
    return {
      circleUrl:
        "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png", //默认头像
      userInfo: {}, //管理员基本信息
      uploadUrl: "", //头像上传路径
      token: { Authorization: "" }, //token
    };
  },
  created() {
    this.downloadManagerAvatar();
    this.initUserInfo();
    this.setToken();
    this.uploadUrl = AVATAR_UPLOAD_PATH;
  },
  methods: {
    //下载用户头像
    async downloadManagerAvatar() {
      let params = {
        avatarUrl: this.$store.state.user.userInfo.avatarUrl,
      };
      let res = await downloadAvatar(params);
      let avatar_img = document.querySelector("#user-avatar-img");
      let imageType = res.type; //获取图片类型
      const blob = new Blob([res], { type: imageType });
      const imageUrl = (window.URL || window.webkitURL).createObjectURL(blob);
      avatar_img.src = imageUrl;
      avatar_img.onload = function (e) {
        window.URL.revokeObjectURL(avatar_img.src); //释放URL.createObjectURL()创建的对象
      };
    },
    async initUserInfo() {
      let res = await getUserDetails();
      if (res.code !== 0) {
        this.$message.error("获取用户基本信息失败");
        return;
      }
      this.userInfo = res.data;
    },
    setToken() {
      this.token.Authorization = getToken();
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    beforeAvatarUpload(file) {
      console.log("type", file.type);
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/jpg" ||
        file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 jpg/jpeg/png 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    handleExceed(files, fileList) {
      this.$message.warning("文件超出个数限制");
    },
    uploadSuccess(res, file, fileList) {
      if (res.code == 0) {
        this.updateUserInfo();
        this.$message.success("上传成功");
        location.reload();
      }
    },
    async updateUserInfo() {
      let res = await getUserInfo();
      if (res.code == 0) {
        this.$store.dispatch("user/setIsManager", res.data.isManager);
        if (res.data.isManager) {
          this.$store.dispatch("user/setUserInfo", res.data.manager);
        } else {
          this.$store.dispatch("user/setUserInfo", res.data.user);
        }
      }
    },
    async updateInfo() {
      let user = this.userInfo;
      let flag = validEmail(user.email);
      if (!flag) {
        this.$message.warning("邮箱格式错误");
        return;
      }
      flag = validIdCard(user.idCard);
      if (!flag) {
        this.$message.warning("省份证格式错误");
        return;
      }
      user.gender = user.gender === "男" ? "1" : "0";
      //发送更新请求
      let res = await updateUserInfo(user);
      if (res.code == 0) {
        this.$message.success("更新成功！");
        location.reload();
      }
    },
  },
};
</script>

<style lang="less" scoped>
.container {
  padding: 10px;
  display: flex;
  flex-direction: column;
}
.header {
  border-radius: 10px 10px 0px 0px;
  display: flex;
  align-items: center;
  width: 70%;
  justify-content: space-between;
  background: rgb(255, 255, 255);
  border-bottom: 1px solid rgb(217, 212, 212);
  .header-left-item {
    padding: 20px;
    display: flex;
    flex-direction: row;
    align-items: center;
    div {
      margin: 5px;
    }
  }
  .header-right-item {
    padding: 10px;
  }
}
.my-content {
  padding-bottom: 0px;
  border-radius: 0px 0px 10px 10px;
  background: rgb(255, 255, 255);
  width: 70%;
  .my-content-item {
    padding-right: 30px;
    padding-top: 20px;
  }
}

#user-avatar-img {
  height: 90px;
  width: 90px;
  border-radius: 50px;
}
</style>